package com.ls.controller;


import com.ls.entity.ProductDTO;
import com.ls.entity.Result;
import com.ls.pojo.Product;
import com.ls.service.IProductService;
import com.ls.util.PageData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @Value("${spring.cloud.client.ip-address}")
    private String host;

    @Value("${server.port}")
    private String port;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/{id}")
    public Result<Product> findById(@PathVariable Integer id) {

        Product product = productService.getById(id);
        return new Result(200, "查询商品成功"+host+":"+port, product);
    }

    @GetMapping("/add")
    public Result add() {
        return new Result(200, "添加商品成功"+host+":"+port);
    }


    @GetMapping("/updateStock/{id}")
    public Result updateStockById(@PathVariable Integer id,String token) {
        if (StringUtils.isEmpty(token)){
            return new Result(500,"非法的请求");
        }
        Boolean flag =stringRedisTemplate.delete("idempotent:"+token);
        if (!flag){
            return new Result<>(500,"重复的请求");
        }


        Integer upd = productService.updateStockById(id);
       if (upd<=0){
           return new Result(500, "扣减库存失败"+host+":"+port);
       }

        return new Result(200, "扣减库存成功"+host+":"+port);
    }

    @ApiOperation("分页+条件")
    @PostMapping("/page/{currentPage}/{pageSize}")
    public Result getPage(@PathVariable Integer currentPage,
                          @PathVariable Integer pageSize,
                          @RequestBody ProductDTO productDTO) {
        //1.数据校验
        //2.调用方法，拿到返回值
        PageData pageData = productService.getPageData(currentPage, pageSize, productDTO);
        //3.返回数据
        return new Result<>(200,"分页查询成功",pageData);

    }


    @ApiOperation("根据id删除")
    @DeleteMapping("/delete/{id}")
    public Result deleteProduct(@PathVariable String id) {

        boolean b = productService.removeById(id);

        return new Result(200,"删除成功");
    }

    @ApiOperation("根据id查询")
    @GetMapping("/get/{id}")
    public Result getProductById(@PathVariable String id) {
        Product product = productService.getById(id);

        return new Result(200,"新增成功",product);
    }


    @ApiOperation("新增")
    @PostMapping("/add")
    public Result addProduct(@RequestBody Product product) {

        boolean save = productService.save(product);
        return new Result<>(200,"新增成功");
    }

}

